#include "Message.h"
#include <memory.h>

Message::Message(void)
{
}

Message::~Message(void)
{
}

int Message::Encode(char type, char* buffer, int offset, int length)
{
	if (length > 10240 - 2 - 4 - 1)
	{
		length = 10240 - 2 - 4 - 1;
	}

	_type = type;
	_length = length + 7;

	// magic number
	_message[0] = 0xb3;
	_message[1] = 0xdc;

	// type
	_message[2] = type;

	// length  little-endian
	_message[3] = length;
	_message[4] = length >> 8;
	_message[5] = length >> 16;
	_message[6] = length >> 24;
	memcpy(_message+7, buffer+offset, length);

	return length;
}

int Message::Decode(char* buffer, int offset, int length)
{
	char *raw = buffer+offset;
	if (raw[0] != 0xb3 || raw[1] != 0xdc)
	{
		return -1;
	}

	if (length > 10240)
	{
		length = 10240;
	}

	_type = raw[2];
	_length = length;

	return length;
}

int Message::GetEncodedMessage(char* buffer, int offset, int length)
{
	if (length < _length)
	{
		return -1;
	}

	memcpy(buffer+offset, _message, _length);
	return _length;
}

int Message::GetDecodedMessage(char* buffer, int offset, int length)
{
	if (length < _length - 7)
	{
		return -1;
	}

	memcpy(buffer+offset, _message+7, _length-7);
	return _length - 7;
}